package com.cloudgateway9527.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局日志过滤器
 * 记录所有通过网关的请求
 */
@Component
public class GlobalLogFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(GlobalLogFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 记录请求信息
        logger.info("Gateway Request: {} {} from {}", 
                request.getMethod(), 
                request.getURI(), 
                request.getRemoteAddress());
        
        // 记录请求头信息（可选）
        if (logger.isDebugEnabled()) {
            request.getHeaders().forEach((name, values) -> 
                logger.debug("Header: {} = {}", name, values));
        }
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        return chain.filter(exchange).then(
            Mono.fromRunnable(() -> {
                // 记录响应时间
                long endTime = System.currentTimeMillis();
                logger.info("Gateway Response: {} {} completed in {}ms", 
                        request.getMethod(), 
                        request.getURI(), 
                        endTime - startTime);
            })
        );
    }

    @Override
    public int getOrder() {
        // 设置过滤器优先级，数值越小优先级越高
        return -1;
    }
}
